﻿using System.Collections.Generic;
using System.Linq;
using K9Nano.AspNetCore.Extensions;
using K9Nano.Authorization;
using K9Nano.Dependency;
using K9Nano.Share.Exceptions;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace K9Nano.AspNetCore.Authorization
{
    public class DefaultApiResourceProvider : IApiResourceProvider, ISingletonDependency
    {
        public IReadOnlyList<IApiResource> Resources { get; }

        public DefaultApiResourceProvider(IActionDescriptorCollectionProvider provider)
        {
            Resources = provider.ActionDescriptors.Items
                .Select(GetApiResource)
                .ToList();
        }

        private static IApiResource GetApiResource(ActionDescriptor actionDescriptor)
        {
            if (actionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                return controllerActionDescriptor.ToApiResource();
            }

            throw new K9BrokenChangeException();
        }
    }
}